const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

// 存储所有连接的用户：Map<userId, ws>
const clients = new Map();

wss.on('connection', (ws) => {
  let userId = null;

  // 接收客户端消息
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);

      // 注册用户
      if (data.type === 'register') {
        userId = data.userId;
        clients.set(userId, ws);
        console.log(`✅ 用户 ${userId} 已加入聊天室`);
        ws.send(JSON.stringify({ type: 'system', message: `欢迎你，${userId}!` }));
        return;
      }

      // 广播消息
      if (data.type === 'broadcast') {
        console.log(`🌐 ${userId} 发送的广播消息: ${data.message}`);
        for (let [id, clientWs] of clients) {
          if (clientWs.readyState === WebSocket.OPEN) {
            clientWs.send(JSON.stringify({
              type: 'broadcast',
              from: userId,
              message: data.message
            }));
          }
        }
        return;
      }

      // 私信
      if (data.type === 'private') {
        const targetWs = clients.get(data.to);
        if (targetWs && targetWs.readyState === WebSocket.OPEN) {
          console.log(`📩 ${userId} 向 ${data.to} 发送私信: ${data.message}`);
          targetWs.send(JSON.stringify({
            type: 'private',
            from: userId,
            message: data.message
          }));
        } else {
          ws.send(JSON.stringify({ type: 'error', message: '目标用户不在线或不存在' }));
        }
        return;
      }

    } catch (err) {
      console.error('❌ 无效消息格式', err);
      ws.send(JSON.stringify({ type: 'error', message: '无效消息格式' }));
    }
  });

  // 客户端断开连接
  ws.on('close', () => {
    if (userId) {
      clients.delete(userId);
      console.log(`❎ 用户 ${userId} 断开连接`);
    }
  });

  // 客户端出错
  ws.on('error', (err) => {
    console.error('WebSocket 错误:', err);
  });

  // 向新连接的客户端发送欢迎信息
  ws.send(JSON.stringify({ type: 'system', message: '连接成功，请输入您的昵称!' }));
});

console.log('✅ WebSocket 服务器已启动，监听端口 8080');
